package com.atguigu.gmall.starter.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class JSONs {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toStr(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转换JOSN的String异常:{}", obj);
        }
        return null;

    }

//    public static List<CategoryAndChildTo> strToCategoryObj(String s) {
//        List<CategoryAndChildTo> tos = null;
//
//        try {
//            tos = objectMapper.readValue(s, new TypeReference<List<CategoryAndChildTo>>() {
//            });
//        } catch (JsonProcessingException e) {
//            log.error("菜单JSON转对象异常",s);
//        }
//
//        return tos;
//    }

    public static <T> T strToObj(String json, TypeReference<T> tTypeReference) {
        T t = null;
        try {
            t = objectMapper.readValue(json, tTypeReference);
        } catch (JsonProcessingException e) {
            log.error("JSON转对象异常",t);
        }
        return t;
    }

    public static <T> T nullInstance(TypeReference<T> tTypeReference) {
        String json="[]";
        T t = null;
        try {
            t = objectMapper.readValue(json, tTypeReference);
        } catch (JsonProcessingException e) {
            log.error("准备空实例异常:{}",e);
            try {
                t = objectMapper.readValue("{}", tTypeReference);
            } catch (JsonProcessingException ex) {
                log.error("你这不是json");
            }
        }
        return t;

    }
}